package com.miaoshaproject.controller;

import com.miaoshaproject.controller.viewobject.ItemVO;
import com.miaoshaproject.error.BussinessException;
import com.miaoshaproject.response.CommonReturnType;
import com.miaoshaproject.service.ItemService;
import com.miaoshaproject.service.model.ItemModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * Created by kenny on 2019/1/6.
 */
@CrossOrigin(allowCredentials ="true",allowedHeaders = "*")
@Controller
@RequestMapping("/item")
public class ItemController extends BaseController {

    @Autowired
    ItemService itemService;

    @RequestMapping(value="/create",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FROMED})
    @ResponseBody
  public CommonReturnType  createItem(@RequestParam(name="title")String title,
                                      @RequestParam(name="description")String description,
                                      @RequestParam(name="price")BigDecimal price,
                                      @RequestParam(name="stock")Integer stock,
                                      @RequestParam(name="imgUrl")String imUrl) throws BussinessException {

    //封装service 请求

      ItemModel itemModel = new ItemModel();
      itemModel.setTitle(title);
      itemModel.setDescription(description);
      itemModel.setStock(stock);
      itemModel.setPrice(price);
      itemModel.setImgUrl(imUrl);
      ItemModel itemModel1 = itemService.createItem(itemModel);
      ItemVO itemVO = convertVOFromModel(itemModel1);
      return CommonReturnType.create(itemVO);

  }

    @RequestMapping(value="/get",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType  getItem(@RequestParam(name="id")Integer id){
        ItemModel itemModel = itemService.getItemById(id);
        ItemVO itemVO =convertVOFromModel(itemModel);

        return CommonReturnType.create(itemVO);
    }
    @RequestMapping(value="/list",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType  list(){
        List<ItemModel> list = itemService.listIitem();

       List<ItemVO> itemVOList= list.stream().map(itemModel -> {
            ItemVO itemVO = this.convertVOFromModel(itemModel);
            return itemVO;
        }).collect(Collectors.toList());

        return CommonReturnType.create(itemVOList);
    }

  private ItemVO convertVOFromModel(ItemModel itemModel){
      if(itemModel == null){
          return null;
      }
      ItemVO itemVO = new ItemVO();

      BeanUtils.copyProperties(itemModel,itemVO);

      return itemVO;

  }
}
